from uuid import uuid4
from PyQt5.QtWidgets import QMessageBox

from libs.pyqt5braisedpork.controller import generic
from libs.pyqt5braisedpork.errorMap import Code, CodeMap
from libs.response import json_response

from .models import User


class LoginController(generic.NoBorderController):
    """登录控制器类"""
    def __init__(self):
        super().__init__()
        self.db_session = self.get_sqlite3_connect("yeChat.db")  # 创建数据库连接

    def show_register_window(self, window_cls):
        """展示注册框"""
        temp_name = uuid4().hex
        self.__dict__[temp_name] = window_cls()
        self.__dict__[temp_name].show()

    def login(self, other):
        """登录"""
        account = self.lineEdit_account.text()
        password = self.lineEdit_passwd.text()

        if not self.check_not_null((account, password)):  # 非空检验
            return QMessageBox.information(self, f"{Code.NotNullError}", "账户或密码不能为空")

        if (check_res := self.check_user(account, password))["code"] == "0":
            try:
                self.close_to(other)
            except Exception as e:
                return QMessageBox.critical(self, f"{Code.UnknownError}", f"{CodeMap[Code.UnknownError]} {str(e)}")
        else:
            return QMessageBox.information(self, f"{check_res['code']}", check_res["message"])

    def check_user(self, account, password):
        """账户校验"""
        filters = [
            User.ACCOUNT == account,
            User.PASSWORD == password
        ]
        user = self.db_session.query(User).filter(*filters).first()

        if not user:
            return json_response(Code.DataNotExistError, "账户或密码错误")
        return json_response()


class RegisterController(generic.BaseController):
    """注册控制器类"""
    def __init__(self):
        super().__init__()
        self.db_session = self.get_sqlite3_connect("yeChat.db")

    def register(self):
        """注册"""
        account = self.lineEdit_account.text()
        password = self.lineEdit_passwd.text()

        if not account or not password:
            return QMessageBox.information(self.parent(), '信息', '账号或密码不能为空。')

        if self.db_session.query(User).filter(User.ACCOUNT == account).first():
            return QMessageBox.information(self.parent(), f"Error-{Code.DataExistError}", "该用户已被注册")

        user = User(ACCOUNT=account, PASSWORD=password)

        try:
            self.db_session.add(user)
            self.db_session.commit()
            return QMessageBox.information(self.parent(), f"{Code.OK}", "注册成功")
        except Exception as e:
            return QMessageBox.critical(self.parent(), f"{Code.UnknownError}", f"{str(e)}")
